package com.ruoyi.system.controller;


import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.controller.es.dto.EsSearch;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.FyProjectVo;
import com.ruoyi.system.domain.vo.HomeCountVo;
import com.ruoyi.system.domain.vo.web.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.util.Page;
import com.ruoyi.system.util.PageUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/web")
public class WebController extends BaseController {
    @Autowired
    private IFyDataService fyDataService;
    @Autowired
    private IFyProjectService fyProjectService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IFyPeopleService fyPeopleService;
    @Autowired
    private IFyResourcesService fyResourcesService;
    @Autowired
    private IFyPolicyService fyPolicyService;
    @Autowired
    private IFyInfoService fyInfoService;
    @Autowired
    private IFyMessageService fyMessageService;
    @Autowired
    private IFyImageService fyImageService;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Resource
    private ElasticsearchRestTemplate template;
    @GetMapping("/home")
    public AjaxResult count()
    {
        Map<String,Object> rmap= redisCache.getCacheObject("home:count");
        if (rmap!=null){
            return AjaxResult.success(rmap);
        }
        HomeCountVo homeCountVo=new HomeCountVo();
            homeCountVo= fyDataService.selectHomecount();
            homeCountVo.setType(10);
        //推荐项目
        List<HomeProjectWebVo> webVos=fyProjectService.selectFyProjectListHome();
        //轮播图
        List<FyImage> list = fyImageService.selectFyImageList(null);
        List<WebFyImageVo> imageVos=new ArrayList<>();
        list.stream().forEach(l->{
            WebFyImageVo webFyImageVo=new WebFyImageVo();
            BeanUtils.copyBeanProp(webFyImageVo,l);
            imageVos.add(webFyImageVo);
        });
        Map<String,Object> map=new HashMap<>();
        map.put("count",homeCountVo);
        map.put("project",webVos);
        map.put("image",imageVos);
        //类别

        //资源总量

        //传承人

        //项目

        //非遗扩展资源
        redisCache.setCacheObject("home:count",map);
        return AjaxResult.success(map);
    }

    /**
     * 字典
     * @param dictType
     * @return
     */
    @GetMapping(value = "dictTypegetdata")
    public AjaxResult dictTypegetdata(String dictType)
    {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        List<WebSysDictData> dictData=new ArrayList<>();
        List<WebSysDictData> finalDictData = dictData;
        data.stream().forEach(d->{
            WebSysDictData webSysDictData=new WebSysDictData();
            BeanUtils.copyBeanProp(webSysDictData,d);
            finalDictData.add(webSysDictData);
        });

        if (StringUtils.isNull(dictData))
        {
            dictData = new ArrayList<WebSysDictData>();
        }
        return success(dictData);
    }

    /**
     * 项目列表
     * @param projectName
     * @param projectType
     * @param projectLevel
     * @return
     */
    @GetMapping("/webproject")
    public TableDataInfo webproject(String projectName,String projectType,String projectLevel)
    {
        startPage();
        List<WebProjectVo> webVos=fyProjectService.selectWebProject( projectName, projectType, projectLevel);
        return getDataTable(webVos);
    }

    /**
     * 项目详情
     * @param projectId
     * @return
     */
    @GetMapping("/webprojectinfo")
    public AjaxResult webprojectinfo(Long projectId)
    {

        FyProject project =fyProjectService.selectFyProjectByProjectId(projectId);
        FyProjectVo fyProjectVo=new FyProjectVo();
        BeanUtils.copyBeanProp(fyProjectVo,project);
        if (project.getProjectId()!=null){
            FyPeople fyPeople=new FyPeople();
            fyPeople.setProjectId(project.getProjectId());
            List<FyPeople> peoples=fyPeopleService.selectFyPeopleList(fyPeople);
            List<WebProjectPeopleVo> projectPeopleVos=new ArrayList<>();
            for (FyPeople fp:peoples){
                WebProjectPeopleVo webProjectPeopleVo=new WebProjectPeopleVo();
                BeanUtils.copyBeanProp(webProjectPeopleVo,fp);
                projectPeopleVos.add(webProjectPeopleVo);
            }
            fyProjectVo.setPeoples(projectPeopleVos);
        }
        return AjaxResult.success(fyProjectVo);
    }
    @GetMapping("/webimage")
    public TableDataInfo webimage(FyImage fyImage)
    {
        startPage();
        List<FyImage> list = fyImageService.selectFyImageList(fyImage);
        return getDataTable(list);
    }

    /**
     * 项目、传承人资源 图片
     * @param
     * @return
     */
//    @GetMapping("/webdatajpg")
//    public TableDataInfo webdatajpg(FyData fyData)
//    {
//        startPage();
//        fyData.setDataType(1l);
//        List<FyData> list = fyDataService.selectFyDataList(fyData);
//        return getDataTable(list);
//    }
    @GetMapping("/webdatajpg")
    public AjaxResult webdatajpg(Long dataType,String dataFormat,Long projectId,Long peopleId,String isproject)
    {

        dataType=1l;
        startPage();
        if (projectId!=null){

            List<WebFyDataVo> dataList = fyDataService.selectwebDataListproject( dataType, dataFormat, projectId, peopleId);
            return AjaxResult.success(new PageInfo(dataList));

        }
        if (peopleId!=null){
            if (StringUtils.isEmpty(isproject)){
                isproject="否";
            }
            if (isproject.equals("是")){

                List<WebFyDataVo> dataList = fyDataService.selectwebDataListpeople( dataType, dataFormat, projectId, peopleId);
                return AjaxResult.success(new PageInfo(dataList));
            }else {
                List<WebFyDataVo> dataList = fyDataService.selectwebDataListpeopleshi( dataType, dataFormat, projectId, peopleId);
                return AjaxResult.success(new PageInfo(dataList));
            }


        }


        return AjaxResult.success();
    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }

    /**
     * 项目、传承人资源 音视频
     * @param
     * @return
     */
    @GetMapping("/webdatamp")
    public AjaxResult webdatamp(Long dataType,String dataFormat,Long projectId,Long peopleId,String isproject)
    {

        dataType=2l;
        startPage();
        if (projectId!=null){
            startPage();
            dataFormat="mp3";
            List<WebFyDataVo> listmp3 = fyDataService.selectwebDataListproject( dataType, dataFormat, projectId, peopleId);
            startPage();
            dataFormat="mp4";
            List<WebFyDataVo> listmp4 = fyDataService.selectwebDataListproject( dataType, dataFormat, projectId, peopleId);
            Map<String,Object> map=new HashMap<>();
            map.put("mp3",new PageInfo(listmp3));
            map.put("mp4",new PageInfo(listmp4));

            return AjaxResult.success(map);

        }
        if (peopleId!=null){
            if (StringUtils.isEmpty(isproject)){
                isproject="否";
            }
            if (isproject.equals("是")){
                startPage();
                dataFormat="mp3";
                List<WebFyDataVo> listmp3 = fyDataService.selectwebDataListpeople( dataType, dataFormat, projectId, peopleId);
                startPage();
                dataFormat="mp4";
                List<WebFyDataVo> listmp4 = fyDataService.selectwebDataListpeople( dataType, dataFormat, projectId, peopleId);
                Map<String,Object> map=new HashMap<>();
                map.put("mp3",new PageInfo(listmp3));
                map.put("mp4",new PageInfo(listmp4));

                return AjaxResult.success(map);
            }else {
                startPage();
                dataFormat="mp3";
                List<WebFyDataVo> listmp3 = fyDataService.selectwebDataListpeopleshi( dataType, dataFormat, projectId, peopleId);
                startPage();
                dataFormat="mp4";
                List<WebFyDataVo> listmp4 = fyDataService.selectwebDataListpeopleshi( dataType, dataFormat, projectId, peopleId);
                Map<String,Object> map=new HashMap<>();
                map.put("mp3",new PageInfo(listmp3));
                map.put("mp4",new PageInfo(listmp4));

                return AjaxResult.success(map);
            }


        }

        return AjaxResult.success();
    }
//    @GetMapping("/webdatamp")
//    public AjaxResult webdatamp(Long dataType,String dataFormat,Long projectId,Long peopleId)
//    {
//
//        startPage();
//        dataType=2l;
//        dataFormat="mp3";
//        List<WebFyDataVo> listmp3 = fyDataService.selectwebDataList( dataType, dataFormat, projectId, peopleId);
//        startPage();
//        dataFormat="mp4";
//        List<WebFyDataVo> listmp4 = fyDataService.selectwebDataList( dataType, dataFormat, projectId, peopleId);
//        Map<String,Object> map=new HashMap<>();
//        map.put("mp3",new PageInfo(listmp3));
//        map.put("mp4",new PageInfo(listmp4));
//
//        return AjaxResult.success(map);
//    }
    /**
     * 项目、传承人资源 文件
     * @param fyData
     * @return
     */
    @GetMapping("/webdatapdf")
    public AjaxResult webdatapdf(Long dataType,String dataFormat,Long projectId,Long peopleId,String isproject)
    {
        startPage();
        dataType=3l;
        if (projectId!=null){

            List<WebFyDataVo> dataList = fyDataService.selectwebDataListproject( dataType, dataFormat, projectId, peopleId);
            return AjaxResult.success(new PageInfo(dataList));

        }
        if (peopleId!=null){
            if (StringUtils.isEmpty(isproject)){
                isproject="否";
            }
            if (isproject.equals("是")){

                List<WebFyDataVo> dataList = fyDataService.selectwebDataListpeople( dataType, dataFormat, projectId, peopleId);
                return AjaxResult.success(new PageInfo(dataList));
            }else {
                List<WebFyDataVo> dataList = fyDataService.selectwebDataListpeopleshi( dataType, dataFormat, projectId, peopleId);
                return AjaxResult.success(new PageInfo(dataList));
            }


        }


        return AjaxResult.success();
    }
//    @GetMapping("/webdatapdf")
//    public TableDataInfo webdatapdf(FyData fyData)
//    {
//        startPage();
//        fyData.setDataType(3l);
//        List<FyData> list = fyDataService.selectFyDataList(fyData);
//
//        return getDataTable(list);
//    }

    /**
     * 传承人列表
     * @param peopleName
     * @param projectName
     * @param projectType
     * @param peopleLevel
     * @return
     */
    @GetMapping("/webpeople")
    public TableDataInfo webpeople(String peopleName, String projectName, String projectType, String peopleLevel)
    {
        startPage();
        List<WebPeopleVo> webVos=fyPeopleService.selectWebPeople(  peopleName,  projectName,  projectType,  peopleLevel);
        return getDataTable(webVos);
    }
    @GetMapping( "/webpeoplegetInfo")
    public AjaxResult webpeoplegetInfo(Long peopleId)
    {
        return success(fyPeopleService.selectFyPeopleByPeopleId(peopleId));
    }

    /**
     * 非遗扩展资源
     * @param fyResources
     * @return
     */
    @GetMapping("/webresources")
    public TableDataInfo webresources(FyResources fyResources)
    {
        startPage();
        List<FyResources> webVos=fyResourcesService.selectFyResourcesList(fyResources);
        return getDataTable(webVos);
    }
    @GetMapping("/webresourcesinfo")
    public AjaxResult webresourcesinfo(Long reId)
    {
        FyResources webVos=fyResourcesService.selectFyResourcesByReId(reId);
        return AjaxResult.success(webVos);
    }


    /**
     * 查询政策列表
     */

    @GetMapping("/webpolicy")
    public TableDataInfo webpolicy(String policyTitle)
    {
        startPage();
        List<WebFyPolicyVo> list = fyPolicyService.selectWebPolicyList(policyTitle);

        return getDataTable(list);
    }
    @GetMapping("/webpolicygetInfo")
    public AjaxResult webpolicygetInfo(Long policyId)
    {
        return success(fyPolicyService.selectFyPolicyByPolicyId(policyId));
    }


    /**
     * 查询资讯列表
     */
    @GetMapping("/webinfo")
    public TableDataInfo webinfo(String infoTitle)
    {
        startPage();
        List<WebFyInfoVo> list = fyInfoService.selectWebInfoList(infoTitle);
        return getDataTable(list);
    }
    @GetMapping( "/webinfogetInfo")
    public AjaxResult webinfogetInfo(Long infoId)
    {
        return success(fyInfoService.selectFyInfoByInfoId(infoId));
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @GetMapping("/getmessage")
    public AjaxResult getmessage()
    {
        return success(fyMessageService.selectFyMessageById(1l));
    }

    @GetMapping("essearch")
    public Map<String, Object> essearch(String keyword, Integer pageSize, Integer pageNum){


        //根据一个值查询多个字段  并高亮显示  这里的查询是取并集，即多个字段只需要有一个字段满足即可
        //需要查询的字段
        BoolQueryBuilder bu= QueryBuilders.boolQuery();
        BoolQueryBuilder boolQueryBuilder= QueryBuilders.boolQuery();
        if (StringUtils.isNotEmpty(keyword)){
            // 使用通配符查询实现不分词的模糊搜索
            boolQueryBuilder.should(QueryBuilders.matchQuery("title", keyword ));
            boolQueryBuilder.should(QueryBuilders.matchQuery("content", keyword ));
        }
        bu.must(boolQueryBuilder);

        //构建高亮查询
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(bu)
                .withHighlightFields(
                        new HighlightBuilder.Field("title")
                        ,new HighlightBuilder.Field("content")

                )
                .withHighlightBuilder(new HighlightBuilder().preTags("<span style='color:red'>").postTags("</span>"))
                .build();


        //查询
        SearchHits<EsSearch> search = template.search(searchQuery, EsSearch.class);
        //得到查询返回的内容
        List<SearchHit<EsSearch>> searchHits = search.getSearchHits();

        if (searchHits.size()>0) {
            //设置一个最后需要返回的实体类集合
            List<EsSearch> users = new ArrayList<>();
            //遍历返回的内容进行处理
            for (SearchHit<EsSearch> searchHit : searchHits) {
                //高亮的内容
                Map<String, List<String>> highlightFields = searchHit.getHighlightFields();
                //将高亮的内容填充
                if (StringUtils.isNotEmpty(searchHit.getContent().getTitle())){
                    searchHit.getContent().setTitle(highlightFields.get("title") == null ? searchHit.getContent().getTitle() : highlightFields.get("title").get(0));

                }
                if (StringUtils.isNotEmpty(searchHit.getContent().getContent())){
                    searchHit.getContent().setContent(highlightFields.get("content") == null ? searchHit.getContent().getContent() : highlightFields.get("content").get(0));

                }
               //放到实体类中
                users.add(searchHit.getContent());
            }
            List<Object> list = users.stream().map(e -> (Object) e).collect(Collectors.toList());
            Page page = PageUtil.page(list, pageSize, pageNum);
            List pageList = list.subList(page.getFromIndex(), page.getToIndex());

            return  PageUtil.success(page,pageList);
        }else {
            return PageUtil.error();
        }

    }
    @GetMapping("essearchinfo")
    public AjaxResult essearchinfo(Integer lanmuId,Long id){
        if (lanmuId==1){
            //资源-项目名录
            return   webprojectinfo(id);
        }
        if (lanmuId==2){
            //资源-非遗传承人
            return  webpeoplegetInfo(id);
        }
        if (lanmuId==3){
            //资源-扩展资源
            return  webresourcesinfo(id);
        }
        if (lanmuId==4){
            //政策
            return  webpolicygetInfo(id);
        }
        if (lanmuId==5){
            //资讯
            return webinfogetInfo(id);
        }
       return AjaxResult.success();
    }
}
